<template>
  <div style="display: inline-block" class="cron-wrapper" @click.stop>
    <div class="form" @click.stop>
      <el-row>
        <el-col :span="60">
          <el-radio-group v-model="type" size="large" style="margin-bottom: 20px;width: 500px;" @click.stop>
            <el-radio-button label="每天" />
            <el-radio-button label="每周" />
            <el-radio-button label="每月" />
          </el-radio-group>
        </el-col>
        <el-col :span="5" style="margin-left: 20px">
          <div @click.stop>
            <el-time-picker
              v-model="time"
              placeholder="选择时间"
              size="large"
              style="width: 140px"
              value-format="H:m"
              :popper-options="{
                strategy: 'fixed',
                modifiers: [
                  {
                    name: 'eventListeners',
                    options: {
                      scroll: false,
                      resize: false
                    }
                  }
                ]
              }"
              popper-class="time-picker-popper"
              :teleported="false"
              @click.stop
              @focus.stop
              @blur.stop
              @change.stop
            ></el-time-picker>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <div class="radio-container" v-if="weekRadio" @click.stop>
          <el-radio-group v-model="week" @click.stop>
            <template v-for="item in weekOption" :key="item.cron">
              <el-radio :label="item.cron" @click.stop>{{ item.value }}</el-radio>
            </template>
          </el-radio-group>
        </div>

        <div class="radio-container" v-if="monthRadio" @click.stop>
          <el-radio-group v-model="month" @click.stop>
            <template v-for="item in monthOption" :key="item.cron">
              <el-radio :label="item.cron" @click.stop>{{ item.value }}</el-radio>
            </template>
          </el-radio-group>
        </div>
      </el-row>

      <div class="footer" @click.stop>
        <p class="time-preview" v-if="time">
          当前设置: <span>{{ timePreview }}</span>
        </p>
        <el-button size="default" @click.stop="closeCron">取消</el-button>
        <el-button size="default" type="primary" @click.stop="handleSummit" :disabled="!time">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { ref } from "vue";

export default {
  name: "timerTaskCron",
  props: {
    runTimeStr: ref(),
    timeCronStr: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      visible: false,
      weekRadio: false,
      monthRadio: false,
      value: "",
      type: "每天", // 天\周\月
      week: 1, // 星期几
      month: 1, // 几号
      time: "", // 时间
      weekOption: [
        {
          title: "星期一",
          value: "星期一",
          cron: 1,
        },
        {
          title: "星期二",
          value: "星期二",
          cron: 2,
        },
        {
          title: "星期三",
          value: "星期三",
          cron: 3,
        },
        {
          title: "星期四",
          value: "星期四",
          cron: 4,
        },
        {
          title: "星期五",
          value: "星期五",
          cron: 5,
        },
        {
          title: "星期六",
          value: "星期六",
          cron: 6,
        },
        {
          title: "星期日",
          value: "星期日",
          cron: 7,
        },
      ],
      monthOption: [],
    };
  },
  computed: {
    timePreview() {
      if (!this.time) return '';
      let preview = this.time;
      
      if (this.type === "每天") {
        preview = `每天 ${this.time}`;
      } else if (this.type === "每周") {
        const weekdayName = this.weekOption.find(item => item.cron === this.week)?.value || '';
        preview = `每周${weekdayName} ${this.time}`;
      } else if (this.type === "每月") {
        const day = this.month < 10 ? `${this.month}  号` : `${this.month} 号`;
        preview = `每月${day} ${this.time}`;
      }
      
      return preview;
    }
  },
  watch: {
    type(a, b) {
      if (this.type === "每天") {
        this.weekRadio = false;
        this.monthRadio = false;
      }
      if (this.type === "每周") {
        this.weekRadio = true;
        this.monthRadio = false;
      }
      if (this.type === "每月") {
        this.weekRadio = false;
        this.monthRadio = true;
      }
    },
    week(a, b) {},
    month(a, b) {},
  },
  created() {
    this.initData();
    // 如果有初始值，尝试解析
    if (this.runTimeStr) {
      this.parseRunTimeStr(this.runTimeStr);
    }
  },
  mounted() {
    // 添加全局点击事件处理器，防止点击时间选择器面板时触发父组件的点击事件
    document.addEventListener('click', this.handleGlobalClick);
  },
  unmounted() {
    // 移除全局点击事件处理器
    document.removeEventListener('click', this.handleGlobalClick);
  },
  methods: {
    handleGlobalClick(event) {
      // 如果点击的是时间选择器相关元素，阻止关闭
      if (event.target.closest('.el-time-panel') || 
          event.target.closest('.el-picker-panel') ||
          event.target.closest('.time-picker-popper')) {
        event.stopPropagation();
      }
    },
    initData() {
      let arr = [];
      var hao = "";
      for (let i = 1; i < 32; i++) {
        hao = i < 10 ? "\xa0\xa0号" : "号";

        arr.push({
          title: i + hao,
          value: i + hao,
          cron: i,
        });
      }
      this.monthOption = arr;
    },

    // 尝试解析现有cron表达式
    parseRunTimeStr(cronStr) {
      if (!cronStr) return;
      
      try {
        // 简单解析，仅作参考
        const parts = cronStr.split(' ');
        if (parts.length >= 5) {
          // 尝试解析时间
          if (parts[0] !== '*' && parts[1] !== '*') {
            this.time = `${parts[1]}:${parts[0]}`;
          }
          
          // 判断类型
          if (parts[2] !== '*' && parts[3] === '*' && parts[4] === '*') {
            // 每月指定日期
            this.type = "每月";
            this.month = parseInt(parts[2]);
            this.monthRadio = true;
          } else if (parts[2] === '*' && parts[3] !== '*' && parts[4] === '*') {
            // 每周指定日期
            this.type = "每周";
            this.week = parseInt(parts[3]);
            this.weekRadio = true;
          } else {
            // 每天
            this.type = "每天";
          }
        }
      } catch (e) {
        console.error('解析cron表达式失败', e);
      }
    },

    closeCron() {
      this.$emit("closeTime", true);
      this.type = "每天";
      this.week = 1;
      this.month = 1;
      this.time = '';
    },
    
    handleSummit() {
      if (!this.time) {
        // Element Plus 消息组件更新
        if (this.$message) {
          this.$message({
            message: "请选择时间!",
            type: "warning",
          });
        } else if (window.ElMessage) {
          window.ElMessage.warning("请选择时间!");
        } else {
          alert("请选择时间!");
        }
        return;
      }
      
      let timeCron;
      let clockCornArr = this.time.split(":").reverse();
      
      if (this.type === "每天") {
        timeCron = clockCornArr.join(" ") + " * * *";
      }
      if (this.type === "每月") {
        timeCron = clockCornArr.join(" ") + " " + this.month + " * *";
      }
      if (this.type === "每周") {
        // 每周
        timeCron = clockCornArr.join(" ") + " * " + this.week + " *";
      }
      
      this.$emit("runTime", timeCron);
      this.$emit("closeTime", true);
      this.type = "每天";
      this.week = 1;
      this.month = 1;
      this.time = '';
    },
  },
};
</script>
<style scoped>
.cron-wrapper {
  max-width: 650px;
  width: 100%;
}

.form {
  padding: 12px;
}

.radio-container {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.footer {
  text-align: right;
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
  position: relative;
}

.el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 10px 0;
}

.el-radio {
  margin-right: 15px;
  margin-bottom: 8px;
}

.footer .el-button {
  padding: 8px 20px;
  font-size: 14px;
}

.footer .el-button + .el-button {
  margin-left: 10px;
}

.time-preview {
  position: absolute;
  left: 0;
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.time-preview span {
  color: #409EFF;
  font-weight: 500;
}
</style>

<style>
/* 非scoped全局样式 */
.time-picker-popper {
  z-index: 10000 !important; /* 确保时间选择器弹窗在最上层 */
  background-color: white !important;
  border-radius: 4px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
}

.el-time-panel {
  position: absolute !important;
  z-index: 10000 !important;
  background-color: white !important;
  border-radius: 4px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
}

.el-picker-panel {
  position: absolute !important;
  z-index: 10000 !important;
  background-color: white !important;
  border-radius: 4px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
}

/* 修复时间选择器的样式 */
.el-time-spinner__wrapper {
  max-height: 190px;
  overflow: auto;
  background-color: white !important;
}

.el-time-spinner__item {
  height: 32px;
  line-height: 32px;
  font-size: 12px;
  color: #606266;
}

.el-time-spinner__item.active:not(.disabled) {
  color: #409EFF;
  font-weight: bold;
}

/* 确保弹出时间选择面板的背景色 */
.el-time-panel__content {
  background-color: white !important;
}

.el-time-panel__footer {
  background-color: white !important;
  border-top: 1px solid #e4e7ed;
  padding: 4px;
  text-align: right;
  box-sizing: border-box;
}
</style>
